package com.shanghaionstar.carmanage.pay.alipay;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.more.entity.PackageInfo;
import com.onstar.cn.payme.entity.PaymentInfoEntity;
import com.onstar.cn.payme.response.CreateOrderResponseType;
import com.shanghaionstar.enumtype.PayTypeEnum;

import java.net.URLEncoder;

/**
 * Created by Yonglang Hong on 2016/7/27.
 */
public class AliPayUtil {

    //app支付成功
    public static final int ALIAPP_PAY_SUCCESS = 1000;
    //web支付成功
    public static final int ALIWEB_PAY_SUCCESS = 1001;


    AliPayCheckUtil checkUtil;

    CreateOrderResponseType orderInfo;

    PaymentInfoEntity paymentInfo;

    PackageInfo packageInfo;

    String orderId;

    String alipayType;

    String accountNo;

    Context context;

    public AliPayUtil(Context context) {
        this.context = context;
        setUpCheckUtil();
    }

    PayTypeEnum payTypeEnum;

    private void setUpCheckUtil() {
        checkUtil = new AliPayCheckUtil();
        checkUtil.setCheckListener(new AliPayCheckUtil.AliCheckListener() {
            @Override
            public void onCheckSuccess() {
                switch (payTypeEnum) {
                    case ALIPAYAPP:
                        appPay(orderInfo);
                        break;
                    case ALIPAYWEB:
                        webPay(orderInfo);
                        break;
                }
            }

            @Override
            public void onCheckFail(String result) {
                Log.d("onCheckFail", result);
                aliPayCheckListener.onCheckFail();
            }
        });
    }

    public void setContent(PayTypeEnum payTypeEnum, CreateOrderResponseType orderInfo){
        this.payTypeEnum = payTypeEnum;
        this.orderInfo = orderInfo;
    }

    public void pay(PayTypeEnum payTypeEnum, CreateOrderResponseType orderInfo) {
        this.payTypeEnum = payTypeEnum;
        this.orderInfo = orderInfo;
        setParams();
        checkUtil.checkAlipay(paymentInfo, packageInfo, orderId, alipayType, accountNo);
    }

    public void pay(String sign) {
        checkUtil.checkAlipay(sign);
    }

    private void setParams() {
        Subscriber subscriber = this.orderInfo.getSubscriber();
        if (!CommonUtil.isNull(subscriber.getPhoneNumber())) {
            this.accountNo = subscriber.getPhoneNumber();
        } else if (!CommonUtil.isNull(subscriber.getEmail())) {
            this.accountNo = subscriber.getEmail();
        } else {
            this.accountNo = subscriber.getDefaultAccountID();
        }
        this.alipayType = "APP";
        switch (this.payTypeEnum) {
            case ALIPAYAPP:
                alipayType = "APP";
                break;
            case ALIPAYWEB:
                alipayType = "WAP";
                break;
        }
        this.paymentInfo = this.orderInfo.getPaymentParameters();
        this.packageInfo = this.orderInfo.getPackageInfo();
        this.orderId = this.orderInfo.getOrderId();
    }

    private void appPay(CreateOrderResponseType orderResponseType) {
        String orderInfo = "partner=" + "\"" + orderResponseType.getPaymentParameters().getAlipayPartnerID() + "\"";
        orderInfo += "&";
        orderInfo += "seller_id=" + "\"" + orderResponseType.getPaymentParameters().getAlipaySeller() + "\"";
        orderInfo += "&";
        orderInfo += "out_trade_no=" + "\"" + orderId + "\"";
        orderInfo += "&";
        orderInfo += "subject=" + "\"" + orderResponseType.getPackageInfo().getPackageName() + "\"";
        orderInfo += "&";
        orderInfo += "body=" + "\"" + orderResponseType.getPackageInfo().getPackageName() + "\"";
        orderInfo += "&";
        orderInfo += "total_fee=" + "\"" + orderResponseType.getPackageInfo().getActualPrice() + "\"";
        orderInfo += "&";
        orderInfo += "notify_url=" + "\"" + orderResponseType.getPaymentParameters().getAlipayNotifyURL() + "\"";
        // 接口名称， 定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";
        // 支付类型，定值
        orderInfo += "&payment_type=\"1\"";
        // 字符集，默认utf-8
        orderInfo += "&_input_charset=\"utf-8\"";
        // 超时时间 ，默认30分钟.
        orderInfo += "&it_b_pay=\"30m\"";
        // 商品展示网址,客户端可不加此参数
        orderInfo += "&show_url=\"m.alipay.com\"";
        String sign = AliPayCheckUtil.sign(orderInfo, orderResponseType.getPaymentParameters().getAlipayPrivateKey());
        try {
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        final String info = orderInfo + "&sign=" + "\"" + sign + "\"" + "&" + "sign_type=\"RSA\"";
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((Activity) context);
                // 调用支付接口
                String result = alipay.pay(info,true);
                Log.d("alipay.pay", "result == " + result);
                AlipayResult resultObj = AlipayResult.getInstance();
                resultObj.getResult(result);
                RxBus.getDefault().post(ALIAPP_PAY_SUCCESS, resultObj.getResultStatus());
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            aliWebPayProxy.pay(orderInfo);
        }
    };

    private void webPay(CreateOrderResponseType orderInfo) {
        handler.sendEmptyMessage(0);
    }

    private AliWebPayProxy aliWebPayProxy;

    public void setAliWebPayProxy(AliWebPayProxy aliWebPayProxy) {
        this.aliWebPayProxy = aliWebPayProxy;
    }

    public interface AliWebPayProxy {
        void pay(CreateOrderResponseType orderInfo);
    }

    private AliPayCheckListener aliPayCheckListener;

    public void setAliPayCheckListener(AliPayCheckListener aliPayCheckListener) {
        this.aliPayCheckListener = aliPayCheckListener;
    }

    public interface AliPayCheckListener {
        void onCheckFail();
    }
}
